/**
 * @FileName: CommunicationfeeController.java
 * @Author
 * @Description:
 * @Date 2016年9月19日 下午2:31:22
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.UserFeedback;
import cn.hpclub.server.service.UserFeedbackService;
import cn.hpclub.server.util.ExcelLargeDataUtils;
import cn.hpclub.server.util.SystemConfigUtil;

public class UserfeedbackController extends BaseAdminController<UserFeedback>{

    private static Logger log = LoggerFactory.getLogger(UserfeedbackController.class);

    /**
     * @Title: 获取角色列表
     */
    public void list(){
        log.debug("RoleController.list");
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        setAttrs(searchInfo);
        initParameters();
        findByPageByRoleLevel(searchInfo);
        render("/admin/user_feedback_list.tpl");
    }

    public void export(){
        log.debug("RoleController.list");
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();;
        setAttrs(searchInfo);
        initParameters();
        String select = UserFeedbackService.service.getSqlSelect();
        String sqlExceptSelect = UserFeedbackService.service.getSqlFilter(searchInfo);
        export(select, sqlExceptSelect);
    }

    private void export(String select, String sqlExceptSelect){
        String[] headers = null;
        String[] columns = null;
        headers = new String[] { "姓名", "手机号", "工号", "地市", "区县", "所属机构", "网点编码", "网店类型", "是否客户经理", "反馈类型","故障模块", "反馈时间",
                "反馈内容", "状态" };
        columns = new String[] { "name", "phone", "emp_code", "city", "AreaName", "DisplayName", "NumCode", "className",
                "is_accounts_manager", "type","gzmk", "time", "content", "processState" };
        String name = generateFileName();
        String filePath = getFilePath(name);
        JSONObject jo = null;
        try{
            String exportFileUrl = ExcelLargeDataUtils.exportData(headers, columns, select + sqlExceptSelect, name,
                                                                  filePath);
            jo = createResponseSuccessJSONObject(exportFileUrl);
        }
        catch(IOException e){
            e.printStackTrace();
            jo = createResponseErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    private String getFilePath(String name){
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + name);

        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        log.info("cmccbusiness fileDir = " + fileDir);

        if(!StringUtils.isEmpty(fileDir)){
            filePath = fileDir + "/file/" + name;
        }
        return filePath;
    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "意见反馈" + curTime + ".xlsx";
        return fileName;
    }

    private JSONObject createResponseErrorJSONObject(IOException e){
        JSONObject jo = new JSONObject();
        jo.put("status", 0);
        jo.put("message", "导出失败：" + e.getMessage());
        return jo;
    }

    private JSONObject createResponseSuccessJSONObject(String exportFileUrl){
        JSONObject jo = new JSONObject();
        jo.put("status", 1);
        jo.put("message", "导出成功，点击下载");
        jo.put("url", exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }

    /**
     * @Title: initParameters
     * @Description:初始化页面参数 void
     */
    private void initParameters(){
        String type = getAttr("type");
        if(StrKit.isBlank(type)){
            setAttr("type", -1);
        }
        String state = getAttr("state");
        if(StrKit.isBlank(state)){
            setAttr("state", -1);
        }
        setAttr("guzhangCode", StrKit.isBlank(getAttr("gzmk_option")) ? "-1" : getAttr("gzmk_option"));

        String sql = " select sv.* from sys_code_value sv LEFT JOIN" +
                " sys_code_type st ON st.id=sv.type_id WHERE st.`code`='GZMK' AND sv.is_deleted != 1";
        List<Record> list = Db.find(sql);
        setAttr("gzmk_options",list);
    }

    /**
     * @Title:findByPageByRoleLevel
     * @Description:根据当前管理员所属角色的等级，获取角色列表 void
     */
    private void findByPageByRoleLevel(ConcurrentHashMap<String, String> searchInfo){

        String select = UserFeedbackService.service.getSqlSelect();
        String sqlExceptSelect = UserFeedbackService.service.getSqlFilter(searchInfo);
        Page<UserFeedback> pager = UserFeedback.dao.paginate(getParaToInt(PAGE_NUMBER, 1), getParaToInt(PAGE_SIZE, 10),
                                                             select, sqlExceptSelect);
        /*pager.getList().stream().forEach(userFeedback -> {
            int i = userFeedback.get("module_value") != null ? userFeedback.getInt("module_value") : 0;

            String name = FeedBackEnum.getNameByValue(i);
            userFeedback.set("module_value",name);
        });*/
        /*List<UserFeedback> list = pager.getList();
        for (UserFeedback userFeedback : list) {
            int i = userFeedback.getInt("module_value");
            String name = FeedBackEnum.getNameByValue(i);
            userFeedback.set("module_value",name);
        }*/
        setAttr(PAGER, pager);
    }

    public void updateState(){
        String id = getPara("id");
        try{
            UserFeedbackService.service.updateState(id);
            ajaxJsonSuccessMessage("成功");
        }
        catch(Exception e){
            ajaxJsonErrorMessage("修改状态失败");
        }
    }
}
